package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.admin.pojo.AdLabel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApiServiceImpl implements ApiService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private  AdChannelFeign adChannelFeign;
    /**
     * 频道列表查询
     * @return
     */
    @Override
    public List<AdChannel> getChannelList() {

         //1.从redis中获取
        String channelListJsonList = stringRedisTemplate.opsForValue().get(SystemConstants.REDISKEY_CHANNELLIST);
        List<AdChannel>  channelList = null;
        if (!StringUtils.isEmpty(channelListJsonList)){
            //2.有值者转成list《adChannel》对象
            channelList = JSON.parseArray(channelListJsonList, AdChannel.class);
        }

         //3.如果redis中没有值则
         if (CollectionUtils.isEmpty(channelList)){

             //3.1则调用admin远程服务 ，查询channel的所有频道列表
             ResultVo<List<AdChannel>> listResultVo = adChannelFeign.listAll();

             if (!listResultVo.isSuccess()){
                  throw new LeadNewsException("调用后台查询频道列表失败!");
             }
             channelList = listResultVo.getData();
         }
         //3.2存入redis
         stringRedisTemplate.opsForValue().set(SystemConstants.REDISKEY_CHANNELLIST,JSON.toJSONString(channelList));


        //返回结果集
        return channelList;
    }
}
